//
//  VideoViewController.m
//  Menu
//
//  Created by dllo on 15/7/1.
//  Copyright (c) 2015年 lijiangang. All rights reserved.
//

#import "VideoViewController.h"

@interface VideoViewController ()

@end

@implementation VideoViewController

-(void)dealloc
{
    [_videoTableView release];
    [_searchTableView release];
    [_bakingArray release];
    [_cuttingArray release];
    [_homemadeArray release];
    [_basicsArray release];
    [_videoKindsArray release];
    [_allVideoArray release];
    [_searchVideoArray release];
    [_searchBar release];
    [_searchField release];
    [_searchView release];
    [_controlView release];
    [super dealloc];
}

-(void)viewWillAppear:(BOOL)animated
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"4" forKey:@"number"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isOK = YES;
    self.navigationItem.title = @"视频教程";
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchButtonFunction)] autorelease];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.videoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, MyWidth, MyHeight - 49 - 64)];
    self.videoTableView.backgroundColor = [UIColor whiteColor];
    self.videoTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, MyWidth, MyHeight - 49 - 64)];
    self.searchTableView.backgroundColor = [UIColor whiteColor];
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    
    [self.view addSubview:self.searchTableView];
    [self.view addSubview:self.videoTableView];
    self.videoTableView.delegate = self;
    self.videoTableView.dataSource = self;
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    
    UIImageView *placeImgView = [[UIImageView alloc] initWithFrame:self.videoTableView.frame];
    placeImgView.image = [UIImage imageNamed:@"videoTeaching.png"];
    [self.view addSubview:placeImgView];
    placeImgView.userInteractionEnabled = YES;
    [placeImgView release];
    
    [_videoTableView release];
    [_searchTableView release];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://content.kitchenstories.de/v2/zh/content.json"];
    self.bakingArray = [NSMutableArray array];
    self.basicsArray = [NSMutableArray array];
    self.cuttingArray = [NSMutableArray array];
    self.homemadeArray = [NSMutableArray array];
    self.allVideoArray = [NSMutableArray array];
    self.searchVideoArray = [NSMutableArray array];
    
    [[DataHandle shareData] openDataBase];
//    [[DataHandle shareData] dropVideoCacheTable];
    [[DataHandle shareData] createVideoCacheTable];
    self.bakingArray = [[DataHandle shareData] selectVideoCacheTable:@"baking"];
    self.basicsArray = [[DataHandle shareData] selectVideoCacheTable:@"basics"];
    self.cuttingArray = [[DataHandle shareData] selectVideoCacheTable:@"cutting"];
    self.homemadeArray = [[DataHandle shareData] selectVideoCacheTable:@"homemade"];
    self.allVideoArray = [[DataHandle shareData] selectVideoCacheTable];

    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"loading...";
    [self.HUD show:YES];
    
    [AFNTool get:urlStr Body:nil HttpResult:JSON success:^(id result)
     {
        [[DataHandle shareData] dropVideoCacheTable];
        [[DataHandle shareData] createVideoCacheTable];
        NSMutableDictionary *bigDict = result;
        NSMutableDictionary *dict = [bigDict objectForKey:@"data"];
        NSMutableArray *theArray = [dict objectForKey:@"howToVideos"];
        for (NSMutableDictionary *theDict in theArray)
        {
            VideoModel *theVideo = [[VideoModel alloc] initWithDic:theDict];
            
            if ([theVideo.category isEqualToString:@"baking"])
            {
                [self.bakingArray addObject:theVideo];
                [[DataHandle shareData] insertVideoCacheTable:theVideo];
            }
            if ([theVideo.category isEqualToString:@"basics"])
            {
                [self.basicsArray addObject:theVideo];
                [[DataHandle shareData] insertVideoCacheTable:theVideo];
            }
            if ([theVideo.category isEqualToString:@"cutting"])
            {
                [self.cuttingArray addObject:theVideo];
                [[DataHandle shareData] insertVideoCacheTable:theVideo];
            }
            if ([theVideo.category isEqualToString:@"homemade"])
            {
                [self.homemadeArray addObject:theVideo];
                [[DataHandle shareData] insertVideoCacheTable:theVideo];
            }
            theVideo.bakingDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.bakingArray,@"baking", nil];
            theVideo.basicsDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.basicsArray,@"basics", nil];
            theVideo.cuttingDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.cuttingArray,@"cutting", nil];
            theVideo.homemadeDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.homemadeArray,@"homemade", nil];
            self.videoKindsArray = [NSMutableArray arrayWithObjects:theVideo.bakingDic,theVideo.basicsDic,theVideo.cuttingDic,theVideo.homemadeDic, nil];
            [self.allVideoArray addObject:theVideo];
            [theVideo release];
        }
        [self.videoTableView reloadData];
        [self.HUD hide:YES];
        [placeImgView removeFromSuperview];
    }
    failure:^(NSError *error)
    {
        self.isOK = NO;
//        self.HUD.labelText = @"加载失败";
//        [self.HUD hide:YES afterDelay:1];
    }];
    
    self.searchField = [[UITextField alloc] init];
    self.searchField.delegate = self;
}

-(void)searchButtonFunction
{
    if (self.isOK == NO)
    {
        [self.HUD hide:YES];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
        return;
    }
    
    self.navigationController.navigationBar.hidden = YES;
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, MyWidth, 64)];
    self.searchBar.translucent = YES;
    [self.searchBar setShowsCancelButton:YES];
    for (UIView *view in [[self.searchBar.subviews lastObject] subviews])
    {
        if ([view isKindOfClass:[UIButton class]])
        {
            UIButton *cancelBtn = (UIButton *)view;
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
            [cancelBtn addTarget:self action:@selector(stopSearch:) forControlEvents:UIControlEventTouchUpInside];
            [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
    }
    self.searchBar.delegate = self;
    self.searchBar.layer.borderColor =[UIColor whiteColor].CGColor;
    self.searchBar.backgroundColor = [UIColor whiteColor];
    self.searchBar.placeholder = @"搜索相关视频";
    self.searchField = [[[self.searchBar.subviews firstObject] subviews] lastObject];
    self.searchField.backgroundColor = [UIColor lightGrayColor];
    [self.searchField becomeFirstResponder];
    [self.searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.searchField.layer.cornerRadius = 15;
    [self.searchField setLeftViewMode:UITextFieldViewModeNever];
    self.searchView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.searchView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapFunction)] autorelease];
    [self.searchView addGestureRecognizer:tap];
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.searchBar];
    
    [_searchBar release];
    [_searchView release];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText isEqualToString:@""])
    {
        [self.view bringSubviewToFront:self.videoTableView];
        [self.view bringSubviewToFront:self.searchView];
        [self.view bringSubviewToFront:self.searchBar];
        [self.videoTableView reloadData];
    } else
    {
        [self.view bringSubviewToFront:self.searchTableView];
        [self.view bringSubviewToFront:self.searchBar];
        self.navigationController.navigationBar.hidden = YES;
        [self.searchTableView reloadData];
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchField resignFirstResponder];
    self.navigationController.navigationBar.hidden = NO;
}

-(void)stopSearch:(UIButton *)button
{
    [self.view bringSubviewToFront:self.videoTableView];
    self.navigationController.navigationBar.hidden = NO;
    [self.searchField resignFirstResponder];
}

-(void)tapFunction
{
    [self.view bringSubviewToFront:self.videoTableView];
    self.navigationController.navigationBar.hidden = NO;
    [self.searchField resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.searchTableView)
    {
        return 1;
    }
    if (tableView == self.videoTableView)
    {
        return 4;
    }
    return 0;
}


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.searchTableView)
    {
        return nil;
    }
    
    if (tableView == self.videoTableView)
    {
        if (section == 0)
        {
            return @"关于烘焙";
        }
        if (section == 1)
        {
            return @"关于基础烹调";
        }
        if (section == 2)
        {
            return @"关于刀工";
        }
        if (section == 3)
        {
            return @"关于自制小吃";
        }
        else
        {
            return nil;
        }
    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchTableView)
    {
        [self.searchVideoArray removeAllObjects];
        for (VideoModel *video in self.allVideoArray)
        {
            if ([video.title containsString:self.searchField.text])
            {
                [self.searchVideoArray addObject:video];
            }
        }
        return self.searchVideoArray.count;
    }
    
    if (tableView == self.videoTableView)
    {
        if (section == 0)
        {
            return self.bakingArray.count;
        }
        if (section == 1)
        {
            return self.basicsArray.count;
        }
        if (section == 2)
        {
            return self.cuttingArray.count;
        }
        if (section == 3)
        {
            return self.homemadeArray.count;
        }
        
        else
        {
            return 0;
        }
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *videoMark = @"video";
    VideoTableViewCell *videoCell = [tableView dequeueReusableCellWithIdentifier:videoMark];
    if (videoCell == nil)
    {
        videoCell = [[VideoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:videoMark];
    }

    
    if (tableView == self.searchTableView)
    {
        videoCell.videoModel = [self.searchVideoArray objectAtIndex:indexPath.row];
    }
    
    if (tableView == self.videoTableView)
    {
        if (indexPath.section == 0)
        {
            videoCell.videoModel = [self.bakingArray objectAtIndex:indexPath.row];
        }
        if (indexPath.section == 1)
        {
            videoCell.videoModel = [self.basicsArray objectAtIndex:indexPath.row];
        }
        if (indexPath.section == 2)
        {
            videoCell.videoModel = [self.cuttingArray objectAtIndex:indexPath.row];
        }
        if (indexPath.section == 3)
        {
            videoCell.videoModel = [self.homemadeArray objectAtIndex:indexPath.row];
        }
    }
    videoCell.selectionStyle = UITableViewCellSelectionStyleNone;
    return videoCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120*HEIGHT;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.searchTableView)
    {
        VideoModel *theVideo = [self.searchVideoArray objectAtIndex:indexPath.row];
        NSURL *url = [[NSURL alloc] initWithString:theVideo.link];
        MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
        playerVC.modalPresentationStyle = 5;
        [self presentMoviePlayerViewControllerAnimated:playerVC];
        
        [playerVC release];
    }
    
    if (tableView == self.videoTableView)
    {
        if (indexPath.section == 0)
        {
            VideoModel *theVideo = [self.bakingArray objectAtIndex:indexPath.row];
            NSURL *url = [[NSURL alloc] initWithString:theVideo.link];
            MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
            playerVC.view.backgroundColor = [UIColor whiteColor];
            playerVC.modalPresentationStyle = 5;
            [self presentMoviePlayerViewControllerAnimated:playerVC];
            [playerVC release];
        }
        if (indexPath.section == 1)
        {
            VideoModel *theViedo = [self.basicsArray objectAtIndex:indexPath.row];
            NSURL *url = [[NSURL alloc] initWithString:theViedo.link];
            MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
            playerVC.view.backgroundColor = [UIColor whiteColor];
            playerVC.modalPresentationStyle = 5;
            [self presentMoviePlayerViewControllerAnimated:playerVC];
            
            [playerVC release];
        }
        if (indexPath.section == 2)
        {
            VideoModel *theVideo = [self.cuttingArray objectAtIndex:indexPath.row];
            NSURL *url = [[NSURL alloc] initWithString:theVideo.link];
            MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
            playerVC.view.backgroundColor = [UIColor whiteColor];
            playerVC.modalPresentationStyle = 5;
            [self presentMoviePlayerViewControllerAnimated:playerVC];
            [playerVC release];
        }
        if (indexPath.section == 3)
        {
            VideoModel *theVideo = [self.homemadeArray objectAtIndex:indexPath.row];
            NSURL *url = [[NSURL alloc] initWithString:theVideo.link];
            MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
            playerVC.view.backgroundColor = [UIColor whiteColor];
            playerVC.modalPresentationStyle = 5;
            [self presentMoviePlayerViewControllerAnimated:playerVC];
            [playerVC release];
        }
    }
}

-(void)pushToCollectController
{
    CollectViewController *collectVC = [[CollectViewController alloc] init];
    [self.navigationController pushViewController:collectVC animated:YES];
    [collectVC release];
}

-(void)pushToEssentialController
{
    EssentialViewController *essentialVC = [[EssentialViewController alloc] init];
    [self.navigationController pushViewController:essentialVC animated:YES];
    [essentialVC release];
}

-(void)pushToRandomController
{
    RandomViewController *randomVC = [[RandomViewController alloc] init];
    [self.navigationController pushViewController:randomVC animated:YES];
    [randomVC release];
}













































- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
